/**
 * desc: current time clock
 * author: Joe
 * date: 7/27/2018
 *
 * @param {Number} totalTime, total seconds
 */

coreModule.directive('nClock',
  [
    '$interval', '$log', 'paddingFilter',
    function($interval, $log, paddingFilter) {
      function link(scope, ele) {
        var totalTime = scope.totalTime;
        if (!angular.isNumber(totalTime)) {
          $log.log('invalid clock param', totalTime);
          return;
        }

        var timeoutId = null;

        function updateTime() {
          var cnt = '00 : 00';
          if (totalTime > 0) {
            var min = parseInt(totalTime / 60);
            var sec = totalTime % 60;
            cnt = paddingFilter(min, 2, 0) + ' : ' + paddingFilter(sec, 2, 0);
          }

          ele.find('span').text(cnt);
        }

        timeoutId = $interval(function() {
          if (totalTime <= 0) {
            $interval.cancel(timeoutId);
            return;
          }

          totalTime--;
          updateTime();
        }, 1000);

        ele.on('$destroy', function() {
          $interval.cancel(timeoutId);
        });
      }

      return {
        restrict: 'E',
        scope: {
          totalTime: '=',
        },
        template: '<span class="neuron-clock" style="border: 1px solid #eee; border-radius: 4px; padding: 4px;">00 : 00</span>',
        link: link,
      };
    }
  ]
);
